import { PayloadAction, createSlice } from '@reduxjs/toolkit';
import { ToolkitStore } from '@reduxjs/toolkit/dist/configureStore';

import main from '../main';
import { LoginUser, Record, AppStore, UserState } from '../types';
import { listRequest } from './listReducer';
import { apiGetUserInfo } from '../page/loginPage/api';

interface SuccessParams {
  user: LoginUser;
  permissions: string[];
  roles: string[];
}

const userSlice = createSlice({
  name: 'user',
  initialState: {
    fetching: false,
    loaded: false,
  } as UserState,
  reducers: {
    userRequest: (state: UserState, action: PayloadAction<{ token: string; callback?: Function }>) => {
      state.fetching = true;
      return state;
    },
    userSuccess: (state: UserState, action: PayloadAction<SuccessParams>) => {
      state.fetching = false;
      state.loaded = true;
      state.error = undefined;
      state.user = action.payload.user;
      state.permissions = action.payload.permissions;
      state.roles = action.payload.roles;
      return state;
    },
    userFailure: (state: UserState, action: PayloadAction<string>) => {
      state.fetching = false;
      state.loaded = true;
      state.error = action.payload;
      return state;
    },
    userClear: (state: UserState) => {
      state = {
        fetching: false,
        loaded: false,
      } as Record<LoginUser>;
      return state;
    },
  },
});

export const { userRequest, userSuccess, userFailure, userClear } = userSlice.actions;
export default userSlice.reducer;

export const userEffect = {
  'user/clear': (store: ToolkitStore<AppStore>) => store.dispatch(userClear()),
  'user/userRequest': async (
    store: ToolkitStore<AppStore>,
    action: PayloadAction<{ token: string; callback?: Function }>
  ) => {
    try {
      let res = await apiGetUserInfo(action.payload.token);
      let data = res.data;
      if (data.code === 200) {
        let user: LoginUser = data.data.user;
        let permissions: string[] = data.data.permissions || [];
        let roles: string[] = data.data.roles || [];
        main.user = user;
        main.permissions = permissions;
        main.roles = roles;
        if (main.watermark) {
          main.createWatermark(true);
        }
        store.dispatch(userSuccess({ user, permissions, roles }));
        store.dispatch(listRequest({ model: 'system', table: 'menu', path: 'getRouters' }));
      } else {
        store.dispatch(userFailure(data.msg || '获取失败'));
        main.user = undefined;
        main.permissions = undefined;
        main.roles = undefined;
      }
    } catch (e: any) {
      store.dispatch(userFailure('获取失败'));
      main.user = undefined;
      main.permissions = undefined;
      main.roles = undefined;
    } finally {
      if (action.payload.callback) {
        action.payload.callback!();
      }
    }
  },
};
